/*
 * Subclass van ui_MainWindow
 */
#include "ruleswindow.h"
#include <QDebug>
#include <QtGui>
#include <iostream.h>

/**
 * Constructor
 */
RulesWindow::RulesWindow(QMainWindow *parent) : QMainWindow(parent)
{
	setupUi(this);
	doWindowGeometry(true);
	rulesTableWidget->setDragDropMode(QAbstractItemView::NoDragDrop);
//	rulesTableWidget->setSelectionMode(QAbstractItemView::NoSelection);
	
}
void RulesWindow::init(Value *settings)
{
	this->settings=settings;
	createActions();
	connect(rulesTableWidget,SIGNAL(cellClicked(int,int)),this,SLOT(handleCellClicked(int,int)));
	connect(rulesTableWidget,SIGNAL(cellDoubleClicked(int,int)),this,SLOT(handleCellDoubleClicked(int,int)));
	connect(Ui_RulesWindow::actionEditRule,SIGNAL(triggered()),this,SLOT(actionEditRule()));
	connect(Ui_RulesWindow::actionDeleteRule,SIGNAL(triggered()),this,SLOT(actionDeleteRule()));
	connect(Ui_RulesWindow::actionAddRule,SIGNAL(triggered()),this,SLOT(actionAddRule()));
	connect(Ui_RulesWindow::actionPreferences,SIGNAL(triggered()),this,SIGNAL(showSettings()));
	rulesTableWidget->setAttribute(Qt::WA_PendingResizeEvent);
	startRefreshTimer();


}
void RulesWindow::fillTable(Value rules)
{
	qDebug()<< "filltable";
	//cout << rules << endl;
	QStringList rulesHeaderLabels=QStringList();
	QTableWidgetItem *item=new QTableWidgetItem();
	

	rulesHeaderLabels << tr("nr") << tr("limit") << tr("reserve") << tr("priority") << tr("direction") << tr("filter count") << tr("current rate");

	while(rulesTableWidget->rowCount() > 0)
		rulesTableWidget->removeRow(0);
	rulesTableWidget->clear();
	

	rulesTableWidget->setColumnCount(rulesHeaderLabels.count());
	rulesTableWidget->setHorizontalHeaderLabels(rulesHeaderLabels);
	
	rulesTableWidget->verticalHeader()->hide();

	std::vector <std::string> ruleIndex=rules.getMemberNames();
	

	QString id,limit,itemText;
	
	for(int rulesCount=0; rulesCount<rules.size(); rulesCount++)
	{
		rulesTableWidget->insertRow(rulesCount);

		//ID
		itemText=QString().fromStdString(ruleIndex[rulesCount]);
		item=new QTableWidgetItem();
		item->setText(itemText);
		item->setToolTip(itemText);
		item->setFlags(Qt::ItemIsEnabled);
		rulesTableWidget->setItem(rulesCount,0,item);		

		//Limit
		itemText=QString().fromStdString(rules[ruleIndex[rulesCount]]["limit"].asString());
		item=new QTableWidgetItem();
		item->setText(itemText);
		item->setToolTip(itemText);
		item->setFlags(Qt::ItemIsEnabled);
		rulesTableWidget->setItem(rulesCount,1,item);		
		//Reserve
		itemText=QString().fromStdString(rules[ruleIndex[rulesCount]]["rate"].asString());
		item=new QTableWidgetItem();
		item->setText(itemText);
		item->setToolTip(itemText);	
		item->setFlags(Qt::ItemIsEnabled);
		rulesTableWidget->setItem(rulesCount,2,item);				

		//Priority
		itemText=QString().fromStdString(rules[ruleIndex[rulesCount]]["priority"].asString());
		item=new QTableWidgetItem();
		item->setText(itemText);
		item->setToolTip(itemText);	
		item->setFlags(Qt::ItemIsEnabled);
		rulesTableWidget->setItem(rulesCount,3,item);				
		
		//Reserve
		itemText=QString().fromStdString(rules[ruleIndex[rulesCount]]["direction"].asString());
		item=new QTableWidgetItem();
		item->setText(itemText);
		item->setToolTip(itemText);	
		item->setFlags(Qt::ItemIsEnabled);
		rulesTableWidget->setItem(rulesCount,4,item);				
		
		//Reserve
		itemText=QString().setNum(rules[ruleIndex[rulesCount]]["filters"].size()-1);
		item=new QTableWidgetItem();
		item->setText(itemText);
		item->setToolTip(itemText);	
		item->setFlags(Qt::ItemIsEnabled);
		rulesTableWidget->setItem(rulesCount,5,item);				
		
		//Rate
		itemText="";
		item=new QTableWidgetItem();
		item->setText(itemText);
		item->setToolTip(itemText);	
		item->setFlags(Qt::ItemIsEnabled);
		qDebug() << item->flags();				
		//item->setDragDropMode(QAbstractItemView::NoDragDrop);
		rulesTableWidget->setItem(rulesCount,6,item);			

	}
	emit wantRates();
	doWindowGeometry(false);

}
void RulesWindow::handleCellDoubleClicked(int row,int column)
{
	emit editRule(getSelectedId());
}
void RulesWindow::actionDeleteRule()
{
	emit deleteRule(getSelectedId());
}
void RulesWindow::actionAddRule()
{
	emit addRule();
}
void RulesWindow::actionEditRule()
{
	emit editRule(getSelectedId());
}
void RulesWindow::fillRates(QMap <QString,QString> rates)
{
	for(int rowCount=0; rowCount<rulesTableWidget->rowCount(); rowCount++)
		rulesTableWidget->item(rowCount,rulesTableWidget->columnCount()-1)->setText(rates[rulesTableWidget->item(rowCount,0)->text()]);
}
bool RulesWindow::event(QEvent * event)
{
	//Vang window resize events af.
	if(event->type()==QEvent::Resize)
	{
		doWindowGeometry(false);
	}
	//Vangt window maximize events af.
	if(event->type()==QEvent::WindowStateChange) {
		if(this->windowState()==Qt::WindowMaximized)
		{
			doWindowGeometry(false);
		}
	}
	return QWidget::event(event);
}
void RulesWindow::createActions()
{
}
void RulesWindow::contextMenuEvent(QContextMenuEvent *event)
{
	if(rulesTableWidget->rowCount()==0)
		return;
	if((event->globalPos().x() < this->pos().x() + 2) || (event->globalPos().y() < this->pos().y() + 142) ||
	(event->globalPos().x() > this->pos().x() + rulesTableWidget->width()-2) ||
	event->globalPos().y() >  this->pos().y()+142+ (rulesTableWidget->rowCount()*30)
	)
		return;
	QMenu menu(rulesTableWidget);
	menu.addAction(Ui_RulesWindow::actionEditRule);
	menu.addAction(Ui_RulesWindow::actionDeleteRule);
	selectRow(rulesTableWidget->currentRow());
	menu.exec(event->globalPos());	

}
void RulesWindow::startRefreshTimer()
{
	timer=new QTimer(this);
	connect(timer,SIGNAL(timeout()),this,SLOT(askRates()));
	timer->start(1000);
}
void RulesWindow::askRates()
{
	if(this->isVisible())
		emit wantRates();
}
void RulesWindow::handleCellClicked(int row,int column)
{
	selectRow(row);
}
int RulesWindow::getSelectedId()
{
	for(int rowCount=0; rowCount<rulesTableWidget->rowCount(); rowCount++)
		if(rulesTableWidget->item(rowCount,0)->background()!=QBrush())
			return QString(rulesTableWidget->item(rowCount,0)->text()).toInt();
	return -1;
}
void RulesWindow::selectRow(int row)
{
	QBrush neutral=QBrush();
	QBrush colored=QBrush("#678db2");
	for(int rowCount=0; rowCount<rulesTableWidget->rowCount(); rowCount++)
		for(int columnCount=0; columnCount<rulesTableWidget->columnCount(); columnCount++)
			rulesTableWidget->item(rowCount,columnCount)->setBackground(neutral);	

	for(int columnCount=0; columnCount<rulesTableWidget->columnCount(); columnCount++)
		rulesTableWidget->item(row,columnCount)->setBackground(colored);
}

void RulesWindow::doWindowGeometry(bool init)
{
	int windowHeight;
	int windowWidth;
	int availableTableWidth;
	if(init) {
		QRect desktopGeometry=QApplication::desktop()->availableGeometry();
		int desktopHeight=desktopGeometry.height();
		int desktopWidth=desktopGeometry.width();
		windowHeight=(desktopHeight/100)*80;
		windowWidth=(desktopWidth/100)*90;
		this->resize(windowWidth,windowHeight);
		QPoint pos=QPoint((desktopWidth/100)*5, (desktopHeight/100)*10);
		move(pos);
	}
	else {
		windowHeight=this->height();
		windowWidth=this->width();
	}
	availableTableWidth=windowWidth;

	//set de hoogte en breedte van de tabel.
	rulesTableWidget->setGeometry(QRect(0, 0, availableTableWidth, (windowHeight)));
	//set de refreshbutton op de goede positie.

	//Scale de tabel op lengte van de header labels.
	rulesTableWidget->setColumnWidth(0,55);
//	statsTableWidget->resizeColumnToContents(0);
	availableTableWidth=availableTableWidth-60; //statsTableWidget->columnWidth(0);

	//IP
	rulesTableWidget->setColumnWidth(2,160);
	availableTableWidth=availableTableWidth-160;

	//Facility
	rulesTableWidget->setColumnWidth(4,140);
	availableTableWidth=availableTableWidth-140;

	//Server description
	rulesTableWidget->setColumnWidth(1,availableTableWidth/4);

	//Tijd
	rulesTableWidget->setColumnWidth(3,availableTableWidth/4);

	//Msg descriptionn
	rulesTableWidget->setColumnWidth(5,availableTableWidth/4);

	//Acknoledge
	rulesTableWidget->setColumnWidth(6,availableTableWidth/4);
}
